/**
 * websocket管理
 */
import { getCookie, wsUrl } from "./index";
import Pubsub from "./pubsub";

class Ws {
    constructor(wsPath,uri) {
        this.lockReconnect = false;
        this.websock = null;
        this.timeout = 28 * 1000;//30秒一次心跳;
        this.timeoutObj = null;//心跳心跳倒计时
        this.serverTimeoutObj = null;//心跳心跳倒计时
        this.timeoutnum = null;//断开 重连倒计时
        this.start = this.start.bind(this);
        this.initWebSocket = this.initWebSocket.bind(this);
        this.websocketonopen = this.websocketonopen.bind(this);
        this.websocketonerror = this.websocketonerror.bind(this);
        this.websocketonmessage = this.websocketonmessage.bind(this);
        this.websocketclose = this.websocketclose.bind(this);
        this.wsPath = wsPath;
        this.uri = uri;

    }
    initWebSocket() {
        //建立连接
        //初始化weosocket
        //const wsuri = "ws://sms.填写您的地址.com/websocket/" + this.charId; //ws地址
        let str = getCookie("userInfo") || "{}";
        let userInfo = JSON.parse(str);
        let wsuri = "";
        if(this.uri){
            wsuri = `ws:${wsUrl}/${this.uri}`;
        }else{
            wsuri = `ws:${wsUrl}/${this.wsPath}/websocket.ws?${userInfo.type}&${userInfo.personId}`;
        }
        //建立连接
        this.websock = new WebSocket(wsuri);
        console.log(this.websock)
        //连接成功
        this.websock.onopen = this.websocketonopen;
        //连接错误
        this.websock.onerror = this.websocketonerror;
        //接收信息
        this.websock.onmessage = this.websocketonmessage;
        //连接关闭
        this.websock.onclose = this.websocketclose;
    }
    closeWebsocket(){
        this.websock.close(3000);
    }
    reconnect() {
        //重新连接
        var that = this;
        if (that.lockReconnect) {
            return;
        }
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        that.timeoutnum && clearTimeout(that.timeoutnum);
        that.timeoutnum = setTimeout(function () {
            //新连接
            that.initWebSocket();
            that.lockReconnect = false;
        }, 5000);
    }
    reset() {
        //重置心跳

        //清除时间
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        //重启心跳
        // this.start();
    }
    start() {
        //开启心跳
        var self = this;
        self.timeoutObj && clearTimeout(self.timeoutObj);
        self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
        self.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            if (self.websock.readyState == 1) {
                //如果连接正常
                self.websock.send("heartCheck");
            } else {
                //否则重连
                // self.reconnect();
            }
            self.serverTimeoutObj = setTimeout(function () {
                //超时关闭
                self.websock.close();
            }, self.timeout);
        }, self.timeout);
    }
    websocketonopen(e) {
        //连接成功事件
        console.log("连接成功");
        this.start();
    }

    websocketonerror(e) {
        //连接失败事件
        //错误
        console.log("WebSocket连接发生错误");
        //重连
        this.reconnect();
    }
    websocketclose(e) {
        console.log("websocket连接已断开");
        if (e.code !== 3000) {//自动断开的时候需要重连，3000
            //重连
            console.log(e,"重连中。。。。。")
            this.reconnect();
        }

    }
    websocketonmessage(event) {
        //接收服务器推送的信息
        //打印收到服务器的内容
        let str = event.data || "{}";
        // let str = '{"content":{"takeNumId":"1b764f3a09ab48d78d12012d675842ff","rankNum":"GT0001","takeTime":"1556553023","handleInfo":"1","handleInfoName":"营业执照申请"},"type":"CALLING"}';

        let result = JSON.parse(str);
        console.log(result,"ws接受到的数据");
        let content = result.content || "";
        Pubsub.publish(result.type, content);
        // if(result.content){
        //     Pubsub.publish(result.type, result.content);
        // }else{
        //     console.log("result.content为空");
        // }
        //收到服务器信息，心跳重置
        this.reset();
        //播放声音
    }
}

export default Ws;